<template>
  <div
    class="desal-select-box"
    :class="{
      'desal-select-box-show': type == 'input' ? inputFocus : showSelectPop,
      'disabled-class': disabled,
    }"
    :style="{
      width: width ? width + 'px' : '100%',
      height: height + 'px',
      'font-size': fontSize + 'px',
      'border-radius': borderR + 'px',
      'margin-bottom': mb + 'px',
    }"
    v-ClickOutside="() => (showSelectPop = false)"
    @click="selectBoxClick"
  >
    <div
      class="desal-select-active f-j-sb-a-c"
      :style="{
        'padding-left': pl + 'px',
        'padding-right': pr + 'px',
        height: height + 'px',
      }"
    >
      <div v-if="type == 'select'">
        <span class="select-title" v-if="selectIndex !== ''">
          {{ label ? list[selectIndex][label] : list[selectIndex] }}</span
        >
        <span class="select-p-title ellipsis" v-else> {{ pTitle }}</span>
      </div>

      <input
        v-else
        ref="selectInput"
        class="select-input"
        type="text"
        v-model="inputValue"
        @blur.stop="inputBlur"
        @focus.stop="inputFocusChange"
        :placeholder="pTitle"
      />
      <!-- <svg-icon
        name="langshangchuang"
        class="pop-icon"
        :class="{ 'pop-icon-show': showSelectPop }"
      ></svg-icon> -->

      <svg-icon
        name="icon-zk"
        class="pop-icon"
        :class="{ 'pop-icon-show': showSelectPop }"
      ></svg-icon>
    </div>

    <div
      class="desal-select-pop"
      :style="{
        top: height + mb + 'px',
        height: showSelectPop ? list.length * height + 20 + 'px' : '0px',
        'border-radius': borderR + 'px',
        'max-height': 5 * height + 20 + 'px',
        overflow: showSelectPop ? 'auto' : 'hidden',
      }"
    >
      <div
        class="desal-select-item f-a-c"
        :style="{
          height: height + 'px',
          'padding-left': pl + 'px',
          'padding-right': pr + 'px',
          'font-size': fontSize + 'px',
        }"
        v-for="(item, index) in list"
        :key="index"
        @click.stop="selectClick(item, index)"
      >
        <div class="ellipsis">
          {{ label ? list[index][label] : list[index] }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import ClickOutside from "element-plus/lib/directives/click-outside/index";
import {
  defineComponent,
  reactive,
  toRefs,
  onUnmounted,
  onMounted,
  computed,
  getCurrentInstance,
  ref,
  watch,
} from "vue";
export default defineComponent({
  emits: ["inputChange", "update:value", "selectChange"],
  directives: { ClickOutside },
  props: {
    height: {
      type: Number,
      default: 42,
    },
    width: {
      type: Number,
      default: 0,
    },
    list: {
      type: Array,
      default: () => [],
    },
    borderR: {
      type: Number,
      default: 10,
    }, //圆角
    pl: {
      type: Number,
      default: 20,
    }, //左内边距
    pr: {
      type: Number,
      default: 10,
    }, //有内边距
    mb: {
      type: Number,
      default: 10,
    }, //下边距
    fontSize: {
      type: Number,
      default: 14,
    },
    type: {
      type: String,
      default: "select",
      // default: "input",
    }, //类型
    label: {
      type: String,
      default: "",
    }, //
    pTitle: {
      type: String,
      default: "请选择",
    },
    valueKey: {
      type: String,
      default: "",
    }, //值key
    value: {
      type: [String, Number, Array],
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { attrs, slots, emit }) {
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const store = useStore();
    let selectInput = ref(null);
    let data = reactive({
      showSelectPop: false, //弹显示隐藏
      inputValue: "", //输入框输入值
      selectIndex: "", //下拉选中下标
      inputFocus: false, //输入框焦点
      searchMoxingTimer: null, //查询定时器
      propsValueOnce: true,
    });

    // 监听输入框
    watch(
      () => data.inputValue,
      (newVal, oldVal) => {
        // if (newVal) {
        //   data.showSelectPop = true;
        // } else {
        //   // if (!props.list.length) {
        //     data.showSelectPop = false;
        //   // }
        // }
        clearTimeout(data.searchMoxingTimer);
        data.searchMoxingTimer = setTimeout(() => {
          // moxingNameClick(val)
          emit("inputChange", newVal);
        }, 100);
      }
    );

    // 下拉框外层点击
    let selectBoxClick = () => {
      if (props.disabled) return;

      if (props.type == "input") {
        selectInput.value.focus();
        data.inputFocus = true;
      } else {
        data.showSelectPop = !data.showSelectPop;
      }
    };

    // 输入框失去焦点
    let inputBlur = () => {
      data.inputFocus = false;
      data.inputValue = "";
      setTimeout(() => {
        data.showSelectPop = false;
      }, 100);
    };

    // 输入框获得焦点
    let inputFocusChange = () => {
      data.showSelectPop = true;
      // console.log(data.showSelectPop);
    };

    // 弹框选中
    let selectClick = (item, index) => {
      data.showSelectPop = false;
      data.selectIndex = index;
      // if(selectInput.value){
      //   proxy.$nextTick(()=>{
      //     selectInput.value.blur();
      //   })
      // }
      // console.log(item);
      emit("update:value", props.valueKey === "" ? item : item[props.valueKey]);
      emit("selectChange", { value: item, index });
    };

    // 输入框输入
    // let inputChange = (e) =>{
    //   clearTimeout(data.searchMoxingTimer);

    //   data.searchMoxingTimer = setTimeout(()=>{
    //     // moxingNameClick(val)
    //     emit("inputChange",e.target.value);
    //   },500)
    //   // emit("inputChange",e.target.value);
    //   // console.log(e.target.value);
    // };

    // 监听数据回显
    watch(
      () => props.value,
      (newVal, oldVal) => {
        // console.log(newVal);
        proxy.$nextTick(() => {
          if (props.value !== "") {
            // data.propsValueOnce = false;
            props.list.forEach((item, index) => {
            let itemValue = props.valueKey === "" ? item : item[props.valueKey];
              if (Array.isArray(props.value)) {
                props.value.forEach((ite) => {
                  if (ite == itemValue) {
                    selectClick(item, index);
                  }
                });
              } else {
                if (itemValue == props.value) {
                  selectClick(item, index);
                }
              }
            });
          } else if (props.value === "") {
            data.propsValueOnce = true;
            data.inputValue = ""; //输入框输入值
            data.selectIndex = ""; //下拉选中下标
          }
        });
      },
      {
        immediate: true,
      }
    );

    // 通过value 回显数据
    onMounted(() => {});

    return {
      inputFocusChange,
      // inputChange,
      inputBlur,
      selectBoxClick,
      selectInput,
      selectClick,
      ...toRefs(data),
    };
  },
});
</script>
<style lang="scss" scoped>
.desal-select-box {
  position: relative;
  // border-radius: 10px 10px 10px 10px;
  opacity: 1;
  border: 1px solid #ececec;
  cursor: pointer;
  transition: all 0.2s;
  background: #ffffff;
  box-sizing: border-box;

  .desal-select-active {
    width: 100%;
    .select-title {
      color: #000000;
    }

    .select-p-title {
      color: #656f79;
      // flex: 1;
      display: inline-block;
      width: 100%;
    }

    .pop-icon {
      transition: all 0.3s;
    }
    .pop-icon-show {
      transform: rotate(-180deg);
    }
    .select-input {
      border: none;
    }
  }
  .desal-select-pop {
    position: absolute;
    background: #ffffff;
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.1);
    // border-radius: 10px;
    width: 100%;

    transition: all 0.3s;
    z-index: 20;

    > div.desal-select-item:first-child {
      margin-top: 10px;
    }
    > div.desal-select-item:last-child {
      margin-bottom: 10px;
    }
    .desal-select-item {
      z-index: 10;
      &:hover {
        background: rgba(100, 200, 220, 0.12);
        color: #64c8dc;
      }
    }
  }
}
.desal-select-box-show {
  border-color: #64c8dc !important;
}
.disabled-class {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 滚动条整体样式 */
.desal-select-pop::-webkit-scrollbar {
  width: 3px;
  height: 3px;
  width: 5px !important;

}

/* 滚动条滑块样式 */
.desal-select-pop::-webkit-scrollbar-thumb {
  background-color: #ececec;
  border-radius: 5px;
}

/* 滚动条轨道样式 */
.desal-select-pop::-webkit-scrollbar-track {
  background-color: #f7f9fa;
  height: 80% !important;


}

/* 鼠标悬停时滚动条轨道样式 */
.desal-select-pop::-webkit-scrollbar-track:hover {
  background-color: #f7f9fa;

}

/* 滚动条滑块样式 */
</style>
